<template>
  <view class="preview-page">
    <view class="preview-warp" v-if="info">
      <swiper circular :current="currentIndex" @change="prevAndNext">
        <swiper-item v-for="(item, index) in dataList" :key="item._id">
          <image
            v-if="lookList.includes(index)"
            class="image"
            @click="showMask"
            :src="item.picurl"
            mode="aspectFill">
          </image>
        </swiper-item>
      </swiper>

      <view class="mask" v-if="!maskState">
        <view
          class="goback"
          @click="goback"
          :style="{
            top: getStatusBarHeight() + 4 + 'px',
          }">
          <uni-icons
            class="white"
            type="back"
            color="#ffffff"
            size="16"></uni-icons>
        </view>
        <view class="number">{{ currentIndex + 1 }}/{{ dataList.length }}</view>
        <view class="time">
          <uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
        </view>
        <view class="date">
          <uni-dateformat :date="Date.now()" format="MM月dd号"></uni-dateformat>
        </view>
        <view class="footer">
          <view class="box" @click="showInfo">
            <uni-icons type="info" size="24"></uni-icons>
            <text>信息</text>
          </view>
          <view class="box" @click="showScore">
            <uni-icons type="star" size="24"></uni-icons>
            <text>{{ info.score }}分</text>
          </view>
          <view class="box" @click="downloadImage">
            <uni-icons type="download" size="24"></uni-icons>
            <text>下载</text>
          </view>
        </view>
      </view>

      <!-- 壁纸信息 -->
      <uni-popup class="popup-info" type="bottom" ref="infoRef">
        <view class="popup-box">
          <view class="header">
            <view class="title">壁纸信息</view>
            <view class="close" @click="closeInfo">
              <uni-icons class="icon" type="closeempty" size="18"></uni-icons>
            </view>
          </view>
          <scroll-view scroll-y>
            <view class="body">
              <view class="row" v-for="item in infoState" :key="item.label">
                <template v-if="item.value">
                  <view
                    class="label"
                    :style="{
                      '--spacing': spacing(item.label),
                    }">
                    <text> {{ item.label }}</text
                    >:
                  </view>

                  <view class="value rate" v-if="item.field === 'score'">
                    <uni-rate readonly :value="item.value" size="20" />
                    <text>{{ item.value }}分</text>
                  </view>

                  <view
                    class="value tag-list"
                    v-else-if="item.field === 'tabs'">
                    <text class="tag" v-for="tag in item.value" :key="tag">
                      {{ tag }}
                    </text>
                  </view>

                  <text class="value string" v-else selectable>
                    {{ item.value }}
                  </text>
                </template>
              </view>
              <view class="copyright">
                声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台。
                邮箱：963249783@qq.com，管理员将删除侵权壁纸，维护您的权益。
              </view>
            </view>
          </scroll-view>
        </view>
      </uni-popup>

      <!-- 我要评分 -->
      <uni-popup
        class="popup-score"
        type="dialog"
        ref="scoreRef"
        :is-mask-click="false">
        <view class="popup-box">
          <view class="header">
            <view class="title">{{ scoreState.title }}</view>
          </view>
          <view class="body">
            <view class="rate">
              <uni-rate
                v-model="scoreState.score"
                allowHalf
                size="36"></uni-rate>
              <text>{{ scoreState.score }}分</text>
            </view>
          </view>
          <view class="footer">
            <button @click="closeScore">取消</button>
            <button
              :disabled="
                scoreState.disabled ? scoreState.disabled : !scoreState.score
              "
              @click="makeScoring">
              确认
            </button>
          </view>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { apiMakeScore, apiDownload, apiDetailWall } from '@/api'
import { getStatusBarHeight } from '@/utils/system.js'

const id = ref(0)
const name = ref('默认分类')
const classList = ref([])
const dataList = ref([])
const info = ref({})
const currentIndex = ref(1)
const lookList = ref([])

const scoreState = ref({
  title: '我要评分',
  score: 0,
  disabled: false,
})
const showScoreData = () => {
  if (info.value.userScore) {
    scoreState.value.disabled = true
    scoreState.value.title = '～已评分～'
    scoreState.value.score = info.value.userScore
  } else {
    scoreState.value.disabled = false
    scoreState.value.title = '我要评分'
    scoreState.value.score = 0
  }
}

onLoad(async e => {
  id.value = e.id
  name.value = e.name

  if (e.type === 'share') {
    classList.value = await apiDetailWall({ id: id.value })
  } else {
    classList.value = uni.getStorageSync('b-classlist') || []
  }
  console.log('%c Line:140 🥑 classList', 'color:#ea7e5c', classList.value)

  dataList.value = classList.value.map(item => {
    return {
      ...item,
      picurl: item.smallPicurl.replace('_small.webp', '.jpg'),
    }
  })

  const current = dataList.value.findIndex(item => item._id === id.value)
  info.value = dataList.value[current]
  initByInfo()

  const len = dataList.value.length
  const [before, after] = [
    current === 0 ? len - 1 : current - 1,
    current === len - 1 ? 0 : current + 1,
  ]
  currentIndex.value = current
  lookList.value.push(before, current, after)
})

const prevAndNext = e => {
  const current = e.detail.current
  info.value = dataList.value[current]
  currentIndex.value = current
  initByInfo()

  const len = dataList.value.length
  if (lookList.value.length === len) return

  const [before, after] = [
    current === 0 ? len - 1 : current - 1,
    current === len - 1 ? 0 : current + 1,
  ]
  if (!lookList.value.includes(before)) lookList.value.push(before)
  if (!lookList.value.includes(after)) lookList.value.push(after)
}

const initByInfo = () => {
  if (Number.isNaN(+info.value.score)) info.value.score = 4
  showScoreData()
  setInfoState({ ...info.value })
}

const maskState = ref(false)
const showMask = () => (maskState.value = !maskState.value)

const infoRef = ref(null)
const showInfo = () => infoRef.value.open()
const closeInfo = () => infoRef.value.close()
const infoState = ref([
  { field: '_id', label: '壁纸编号', value: String(Date.now()) },
  { field: 'name', label: '分类', value: '默认分类' },
  { field: 'nickname', label: '发布者', value: '落雨成花' },
  { field: 'score', label: '评分', value: 4 },
  {
    field: 'description',
    label: '介绍',
    value: '图片的介绍图片的介绍图片的介绍图片的介绍图片的介绍图片的介绍',
  },
  { field: 'tabs', label: '标签', value: ['明星', '美女', '时尚'] },
])
const setInfoState = data => {
  infoState.value.forEach(item => {
    if (item.field === 'name') {
      item.value = name.value
    } else {
      item.value = data[item.field]
    }
  })
}

const spacing = computed(() => value => {
  const len = value.length
  const pad = 4 - len
  if (pad === 1) return pad / 2 + 'em'
  return pad === 2 ? pad + 'em' : 'normal'
})

const scoreRef = ref(null)
const showScore = () => scoreRef.value.open()
const closeScore = () => {
  scoreRef.value.close()
  scoreState.value.score = 0
}
const makeScoring = async () => {
  const { classid, _id: wallId } = info.value
  const res = await apiMakeScore({
    classid,
    wallId,
    userScore: scoreState.value.score,
  })
  console.log('%c Line:215 🍷 res', 'color:#6ec1c2', res)

  classList.value[currentIndex.value].userScore = scoreState.value.score
  info.value = { ...info.value, userScore: scoreState.value.score }
  uni.setStorageSync('b-classlist', classList.value)
  closeScore()
}

const goback = () => {
  uni.navigateBack({
    success: () => uni.removeStorageSync('b-classlist'),
    fail: () => uni.reLaunch({ url: '/pages/index/index' }),
  })
}

const downloadImage = async () => {
  // #ifdef H5
  uni.showModal({
    title: '提示',
    content: '请长按保存壁纸',
    showCancel: false,
  })
  // #endif

  // #ifndef H5
  let { classid, _id: wallId } = info.value
  const { errCode, errMsg } = await apiDownload({ classid, wallId })
  console.log('%c Line:242 🍊', 'color:#33a5ff', errCode, errMsg)

  uni.getImageInfo({
    src: info.value.picurl,
    success: ({ path }) => {
      uni.saveImageToPhotosAlbum({
        filePath: path,
        success: () => {
          uni.showToast({
            title: '保存成功',
            icon: 'success',
          })
        },
        fail: err => {
          if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
            uni.showToast({
              title: '保存失败',
              icon: 'fail',
            })
            return
          }
          uni.showModal({
            title: '系统提示',
            content: '需要授权保存相册',
            success: res => {
              uni.getSetting({
                success: ({ authSetting }) => {
                  if (authSetting['scope.writePhotosAlbum']) {
                    uni.showToast({
                      title: '授权成功',
                      icon: 'success',
                    })
                  } else {
                    uni.showToast({
                      title: '授权失败',
                      icon: 'error',
                    })
                  }
                },
                fail: error => {},
              })
            },
          })
        },
        complete: () => {
          uni.hideLoading()
        },
      })
    },
    fail: error => {},
  })
  // #endif
}

onShareAppMessage(() => {
  return {
    title: `手机壁纸 - ` + name.value,
    path: `/pages/preview/preview?id=${id.value}&name=${name.value}&type=share`,
  }
})
</script>

<style lang="scss" scoped>
.preview-warp {
  width: 100%;
  height: 100vh;

  swiper {
    height: inherit;

    .image {
      width: 100%;
      height: 100%;
    }
  }

  .mask {
    --top: 10vh;

    & > view {
      position: absolute;
      left: 0;
      right: 0;
      width: fit-content;
      margin: auto;
      color: $uni-bg-color;
    }

    .goback {
      width: 64rpx;
      height: 64rpx;
      top: 0;
      left: 30rpx;
      margin-left: 0;
      border-radius: 64rpx;
      background-color: #eff0f0;
      background-color: rgba(0, 0, 0, 0.3);
      // filter: grayscale(1) contrast(99) invert(1);
      border: 1rpx solid rgba(255, 255, 255, 0.5);
      box-shadow: 0 0 16rpx 0 $font-color-5;
      backdrop-filter: blur(16rpx);

      display: flex;
      align-items: center;
      justify-content: center;
    }

    .number {
      top: var(--top);
      color: $font-color-5;
      background-color: rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(16rpx);
      border: 1rpx solid rgba(255, 255, 255, 0.5);
      box-shadow: 0 0 16rpx 0 $font-color-5;
      font-size: 28rpx;
      padding: 8rpx 30rpx;
      border-radius: 60rpx;
      letter-spacing: 6rpx;
    }

    .time {
      top: calc(var(--top) + 80rpx);
      color: $white-color;
      font-size: 144rpx;
      text-shadow: 0 3rpx rgba(0, 0, 0, 0.3);
    }

    .date {
      top: calc(var(--top) + 260rpx);
      font-size: 36rpx;
      text-shadow: 0 3rpx rgba(0, 0, 0, 0.3);
    }

    .footer {
      color: $font-color-1;
      background-color: rgba(255, 255, 255, 0.65);
      bottom: var(--top);
      display: flex;
      align-items: center;
      justify-content: space-around;

      width: 65vw;
      height: 100rpx;
      border-radius: 50rpx;
      box-shadow: 0 3rpx rgba(0, 0, 0, 0.2);
      backdrop-filter: blur(10rpx);

      & > view {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }

      .box {
        padding: 4rpx 30rpx;

        text {
          font-size: 24rpx;
        }
      }
    }
  }
}

.popup-box {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;

  .header {
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    padding-bottom: 30rpx;

    .title {
      color: $font-color-2;
      font-size: $font-size-2;
      font-weight: 500;
      letter-spacing: 3rpx;
    }

    .close {
      position: absolute;
      top: 27rpx;
      right: 32rpx;
      padding: 6rpx 16rpx;
      display: flex;
      place-items: center;

      .icon {
        color: $font-color-4 !important;
      }
    }
  }
}

.copyright {
  color: $font-color-4;
  font-size: $font-size-sm;
  line-height: 1.6;
  padding: 16rpx 40rpx;
  background-color: $border-color-2;
  margin-top: 30rpx;
}

.popup-info {
  scroll-view {
    max-height: 55vh;

    .body {
      .row {
        padding: 0 30rpx;
        display: flex;
        flex-direction: row;
        line-height: 1.8;
        font-size: $font-size;
        padding-bottom: 10rpx;

        .label {
          width: 144rpx;
          color: $font-color-4;
          text-align: right;
          margin-right: 16rpx;

          text {
            white-space: nowrap;
            letter-spacing: var(--spacing);
            margin-right: calc(var(--spacing) * -1);
          }
        }

        .value {
          &.string {
            flex: 1;
            color: $font-color-2;
          }

          &.rate {
            display: flex;
            align-items: center;
            justify-content: center;

            text {
              margin-left: 20rpx;
              color: $font-color-4;
            }
          }

          &.tag-list {
            display: flex;

            .tag {
              display: flex;
              padding: 4rpx 20rpx;
              font-size: $font-size-sm;
              color: $primary-theme-color;
              border: 1px solid $primary-theme-color;
              border-radius: 100rpx;
              margin-left: 10rpx;

              &:first-child {
                margin-left: 0;
              }
            }
          }
        }
      }
    }
  }
}

.popup-score {
  .popup-box {
    width: 80vw;
    border-radius: 20rpx;
    box-shadow: 0 0 20rpx 0 $border-color-4;
  }

  .body {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-bottom: 30rpx;

    .rate {
      padding: 50rpx;
      padding-bottom: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      text {
        width: 100rpx;
        color: $font-color-4;
        font-size: $font-size-2;
        margin-left: 20rpx;
      }
    }

    button {
      width: 192rpx;

      text {
        font-size: $font-size;
        letter-spacing: 16rpx;
        margin-right: -16rpx;
        white-space: nowrap;
      }
    }
  }

  .footer {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    border-top: 1px solid $border-color-3;

    button {
      width: 50%;
      background-color: unset;
      color: #007aff;
      font-size: $font-size-2;
      border-radius: 0;

      &:first-child {
        color: $font-color-4;
        border-right: 1px solid $border-color-4;
      }

      &::after {
        border: none;
        border-radius: 0;
      }

      &[disabled='true'] {
        color: $font-color-4;
      }
    }
  }
}
</style>
